package client;


import java.nio.FloatBuffer;
import java.nio.IntBuffer;

import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector3f;

import shared.Vertex;
import vmo.Chunk;

public class ChunkRender {

	Chunk p_chunk;
	Layer [] m_layers;
	public Matrix4f m_matrix;
	
	public ChunkRender(Chunk chunk)
	{
		p_chunk=chunk;

		m_matrix=new Matrix4f();
		m_matrix.m00=1;	m_matrix.m11=1; m_matrix.m22=1; m_matrix.m33=1;
		Vector3f vec=new Vector3f(); 
		vec.x=p_chunk.m_position.x*16; vec.y=p_chunk.m_position.y*16;
		Matrix4f.translate(vec, m_matrix,m_matrix);
		
		m_layers=new Layer[3];
		for (int i=0;i<3;i++)
		{
			m_layers[i]=new Layer();
		}
	}
	
	public void Discard()
	{
		for (int i=0;i<3;i++)
		{
			if (m_layers[i]!=null)
			{
				m_layers[i].Discard();
			}
		}
	}
	
	public void Swap(Chunk chunk)
	{
		p_chunk=chunk;
		m_matrix.m00=1;	m_matrix.m11=1; m_matrix.m22=1; m_matrix.m33=1;
		m_matrix.m31=0; m_matrix.m30=0;
		Vector3f vec=new Vector3f(); 
		vec.x=p_chunk.m_position.x*16; vec.y=p_chunk.m_position.y*16;
		Matrix4f.translate(vec, m_matrix,m_matrix);		
	}
	
	public void Generate(int level)
	{
		Discard();
		
		if (level>2 && p_chunk.m_tiles[level-2]!=null)
		{
			m_layers[2].Generate(level-2, p_chunk);
		}
		if (level>1 && p_chunk.m_tiles[level-1]!=null)
		{
			m_layers[1].Generate(level-1, p_chunk);
		}
		if (p_chunk.m_tiles[level]!=null)
		{
			m_layers[0].Generate(level, p_chunk);
			m_layers[0].GenerateWidgets(level, p_chunk);
		}
	}
	
	public void Draw(FloatBuffer matrix44Buffer, int matrixloc,int colourloc)
	{
		//set matrix
		m_matrix.store(matrix44Buffer); matrix44Buffer.flip();
		GL20.glUniformMatrix4(matrixloc, false, matrix44Buffer);

		//draw first layer at full colour
		if (m_layers[2].getDraw())
		{
			GL20.glUniform4f(colourloc,0.4F,0.4F,0.4F, 1);		
			m_layers[2].Draw();	
		}		
		if (m_layers[1].getDraw())
		{
			GL20.glUniform4f(colourloc,0.7F,0.7F,0.7F, 1);		

			m_layers[1].Draw();	
		}	
		if (m_layers[0].getDraw())
		{	
			GL20.glUniform4f(colourloc,1.0F,1.0F,1.0F, 1);		
			m_layers[0].Draw();
		}
		//draw 2nd layer at 80%

		//draw 3rd layer at 60%

		GL20.glUniform4f(colourloc,1.0F,1.0F,1.0F, 1);		
	}
	
	public void Draw2ndPass(FloatBuffer matrix44Buffer, int matrixloc,int colourloc)
	{
		m_matrix.store(matrix44Buffer); matrix44Buffer.flip();
		GL20.glUniformMatrix4(matrixloc, false, matrix44Buffer);	
		if (m_layers[0].getDraw())
		{
			m_layers[0].DrawWidgets();
		}	
	}
}
